package com.xlf.service.system.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xlf.common.auth.util.SecurityUtils;
import com.xlf.common.core.constant.UserConstants;
import com.xlf.common.core.exception.BizException;
import com.xlf.common.core.exception.ServiceException;
import com.xlf.common.core.util.BeanCopyUtils;
import com.xlf.common.core.util.StringUtils;
import com.xlf.common.redis.service.RedisCache;
import com.xlf.pojo.system.SysRole;
import com.xlf.pojo.system.SysUser;
import com.xlf.pojo.system.SysUserRole;
import com.xlf.service.system.mapper.SysRoleMapper;
import com.xlf.service.system.mapper.SysUserMapper;
import com.xlf.service.system.mapper.SysUserRoleMapper;
import com.xlf.service.system.service.SysUserRoleService;
import com.xlf.service.system.service.SysUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
* @author 小新
* @description 针对表【sys_user(用户信息表)】的数据库操作Service实现
* @createDate 2023-02-04 16:32:58
*/
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser>
    implements SysUserService {


    @Resource
    SysRoleMapper roleMapper;

    @Resource
    SysUserMapper userMapper;

    @Resource
    SysUserRoleMapper userRoleMapper;


    @Resource
    SysUserRoleService userRoleService;

    @Resource
    RedisCache redisCache;



    @Override
    public SysUser selectUserByUserName(String username) {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUserName,username);
        return getOne(wrapper);
    }

    @Override
    public SysUser selectUser(String username, String userId, String email) {

        SysUser sysUser = null;

        if(StringUtils.isNotEmpty(username))
            sysUser = getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUserName,username));
        else if (StringUtils.isNotEmpty(userId))
            sysUser = getById(userId);
        else if(StringUtils.isNotEmpty(email))
            sysUser = getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getEmail,email));

        return sysUser;
    }

    /**
     * 查询用户所属角色组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(String userName)
    {
        List<SysRole> list = roleMapper.selectRolesByUserName(userName);
        if (CollectionUtils.isEmpty(list))
        {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysRole::getRoleName).collect(Collectors.joining(","));
    }



    @Override
    public boolean resetUserPwd(String userName, String encryptPassword) {

        return update().set("password",encryptPassword).eq("userName",userName).update();

    }


    /**
     * 校验手机号码是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkPhoneUnique(SysUser user)
    {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.selectOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getPhonenumber, user.getPhonenumber()));
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkEmailUnique(SysUser user)
    {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.selectOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getEmail, user.getEmail()));
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 根据条件分页查询未分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    public List<SysUser> selectUnallocatedList(SysUser user)
    {
        return userMapper.selectUnallocatedList(user);
    }

    /**
     * 校验用户是否允许操作
     *
     * @param user 用户信息
     */
    @Override
    public void checkUserAllowed(SysUser user)
    {
        if (StringUtils.isNotNull(user.getUserId()) && user.admin())
        {
            throw new ServiceException("不允许操作超级管理员用户");
        }
    }

    /**
     * 校验用户是否有数据权限
     *
     * @param userId 用户id
     */
    @Override
    public void checkUserDataScope(Long userId)
    {
        if (!SysUser.admin((Long) SecurityUtils.getUserId()))
        {
            if (getById(userId)==null)
            {
                throw new ServiceException("没有权限访问用户数据！");
            }
        }
    }

    @Override
    public void insertUserAuth(Long userId, Long[] roleIds) {

        //删除角色和用户关联
        userRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId,userId));

        insertUserRole(userId, roleIds);
    }

    @Override
    public SysUser selectUserById(Long userId) {
        return getById(userId);
    }

    @Override
    public Boolean updateUserStatus(SysUser user) {
        return lambdaUpdate().set(SysUser::getStatus,user.getStatus()).eq(SysUser::getUserId,user.getUserId()).update();

    }

    @Override
    public Boolean resetPwd(SysUser user) {
        return lambdaUpdate().set(SysUser::getPassword,user.getPassword()).eq(SysUser::getUserId,user.getUserId()).update();
    }

    @Transactional
    @Override
    public int deleteUserByIds(Long[] userIds) {
        for (Long userId : userIds)
        {
            checkUserAllowed(SysUser.builder().userId(userId).build());
            checkUserDataScope(userId);
        }
        // 删除用户与角色关联
        userRoleService.remove(new LambdaQueryWrapper<SysUserRole>().in(SysUserRole::getUserId,userIds));


        return userMapper.deleteBatchIds(Arrays.stream(userIds).collect(Collectors.toList()));
    }

    @Override
    public String checkUserNameUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.selectOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUserName,user.getUserName()));
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Transactional
    @Override
    public Boolean updateUser(SysUser user) {
        Long userId = user.getUserId();
        // 删除用户与角色关联
        userRoleService.remove(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId,userId));
        // 新增用户与角色管理
        insertUserRole(user);
        user.setPassword(null);
        return updateById(user);
    }

    @Transactional
    @Override
    public Boolean insertUser(SysUser user) {
        //主键回填
        boolean save = save(user);
         // 新增用户与角色管理
        insertUserRole(user);
        return save;
    }

    @Override
    public List<SysUser> selectUserList(SysUser user) {
        return userMapper.selectUserList(user);
    }

    @Override
    public boolean updateUserAvatar(String username, String avatar) {
        return lambdaUpdate().set(SysUser::getAvatar,avatar).eq(SysUser::getUserName,username).update();
    }


    @Override
    public SysUser getUserById(Long id) {
        return getById(id);
    }


    @Override
    public List<SysUser> getUsersByIds(Set<String> ids) {

        if(StringUtils.isEmpty(ids))
            return new ArrayList<>();
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(SysUser::getUserId,ids);
        return list(wrapper);
    }


    @Override
    public SysUser selectUserByEmail(String email) {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getEmail,email);
        return getOne(wrapper);
    }

    @Override
    public void register(SysUser user) {

        if (UserConstants.NOT_UNIQUE.equals(checkUserNameUnique(user)))
        {
            throw new BizException("账号已存在!");
        }
         if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(checkPhoneUnique(user)))
        {
            throw new BizException("手机号码已存在!");

        }
         if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(checkEmailUnique(user)))
        {
            throw new BizException("邮箱账号已存在!");
        }
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));

        if(!insertUser(user))
            throw new BizException("注册失败！");

    }


    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    public void insertUserRole(SysUser user)
    {
        this.insertUserRole(user.getUserId(), user.getRoleIds());
    }

    /**
     * 新增用户角色信息
     *
     * @param userId 用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole(Long userId, Long[] roleIds)
    {
        if (StringUtils.isNotEmpty(roleIds))
        {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>(roleIds.length);
            for (Long roleId : roleIds)
            {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            userRoleService.saveBatch(list);
        }
    }

    /**
     * 根据条件分页查询已分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    public List<SysUser> selectAllocatedList(SysUser user)
    {
        return userMapper.selectAllocatedList(user);
    }




}




